package com.soc.course.sercice.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.soc.course.entity.Chapter;
import com.soc.course.mapper.ChapterMapper;
import com.soc.course.sercice.ChapterService;
import com.soc.course.sercice.TaskUserService;
import com.soc.course.sercice.resEntity.ChapterNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {
    @Autowired
    private ChapterMapper chapterMapper;

    @Autowired
    private TaskUserService taskUserService;

    /**
     * 查询1001课程的章节目录，返回带有层级关系的章节列表
     *
     * @return List<ChapterVO> 带有层级关系的章节列表
     */


    @Override
    public List<ChapterNode> getChapterList(String courseId, String userId) {
        Map<String, ChapterNode> nodeMap = getChapterNodeList(courseId, userId);
        return buildChapterTreeNode(nodeMap);
    }

    private List<ChapterNode> buildChapterTreeNode(Map<String, ChapterNode> nodeMap) {
        List<ChapterNode> roots = new ArrayList<>();

        // 构建章节目录树
        for (ChapterNode node : nodeMap.values()) {
            String parentId = node.getParentId();
            if (parentId.equals("0")) {
                // 根节点
                roots.add(node);
            } else {
                // 非根节点
                ChapterNode parent = nodeMap.get(parentId);
                if (parent != null) {
                    parent.addChild(node);
                }
            }
        }


        // 排序子节点
        for (ChapterNode node : nodeMap.values()) {
            if (node.hasChildren()) {
                node.sortChildren();
            }
        }

        roots.sort(Comparator.comparingInt(ChapterNode::getSortOrder));
        return roots;
    }

    public Map<String, ChapterNode> getChapterNodeList(String courseId, String userId) {
        // 查询1001课程的所有章节
        List<Chapter> chapters = chapterMapper.selectList(
                new QueryWrapper<Chapter>()
                        .eq("course_id", courseId)
                        .orderByAsc("sort_order")
        );
        Map<String, ChapterNode> nodeMap = new HashMap<>();
        Map<String, Long> courseTaskMap = new HashMap<>();

        if (userId != null) {
            courseTaskMap = taskUserService.getCourseTaskMap(courseId, userId);
        }
        // 将所有章节节点加入 map
        for (Chapter chapter : chapters) {
            ChapterNode node = new ChapterNode(chapter.getChapterId(), chapter.getChapterTitle(), chapter.getParentId(), chapter.getSortOrder(), chapter.getResourceCount(), chapter.getVideoCount(),chapter.getRank());
            if (node.getVideoCount() != 0) {
                node.setTaskCount((int) (node.getVideoCount() - courseTaskMap.getOrDefault(node.getChapterId(), 0L)));
            } else {
                node.setTaskCount(0);
            }
            nodeMap.put(chapter.getChapterId(), node);
        }
        return nodeMap;
    }


    /**
     * 添加子章节
     *
     * @param parentId 父章节 ID
     * @param child    子章节实体
     * @return 添加结果
     */
    @Override
    public boolean addChildChapter(String parentId, String courseId, Chapter child) {
        QueryWrapper<Chapter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", parentId);
        List<Chapter> chapters = chapterMapper.selectList(queryWrapper);
        boolean flag = true;
        if (parentId.equals("0")) {
            child.setRank(1);
            child.setSortOrder(chapters.size() + 1);
        } else {
            Chapter parent = getById(parentId);
            if (parent == null) {
                throw new IllegalArgumentException("Invalid parent chapter ID");
            }
            child.setRank(parent.getRank() + 1);
            child.setSortOrder(parent.getChildCount() + 1);
            parent.setChildCount(parent.getChildCount() + 1);
            if (!updateById(parent)) {
                flag = false;
            }
        }
        child.setParentId(parentId);
        child.setCourseId(courseId);

        return save(child) && flag;
    }

    /**
     * 添加同级章节
     *
     * @param parentId   父级章节ID
     * @param newChapter 新章节实体
     * @return 添加是否成功
     */
//    @Override
//    public boolean addSiblingChapter(String parentId, Chapter newChapter) {
//        // 先查询父章节
//        Chapter parentChapter = chapterMapper.selectById(parentId);
//        if (parentChapter == null) {
//            // 父章节不存在，添加失败
//            return false;
//        }
//        // 设置新章节的层级和顺序
//        newChapter.setRank(parentChapter.getRank() + 1);
//        newChapter.setSortOrder(parentChapter.getChildCount() + 1);
//        // 设置新章节的父章节
//        newChapter.setParentId(parentId);
//        // 将新章节添加到父章节的子章节列表中
//        parentChapter.setChildCount(parentChapter.getChildCount() + 1);
//        // 更新父章节
//        return save(newChapter) && updateById(parentChapter);
//    }


    /**
     * 插入章节
     *
     * @param newChapter       章节实体
     * @param siblingChapterId 同级章节id
     * @param parentId         父章节id
     * @return 插入是否成功
     */
    @Override
    public boolean addSiblingChapterBefore(String parentId, String courseId, String siblingChapterId, Chapter newChapter) {
        Boolean flag = true;
        // 先查询同级章节和同级章节的父章节
        Chapter siblingChapter = chapterMapper.selectById(siblingChapterId);
        if (siblingChapter == null) {
            // 同级章节不存在，添加失败
            return false;
        }
        if (parentId.equals("0")) {
            newChapter.setParentId("0");
        } else {
            Chapter parentChapter = chapterMapper.selectById(parentId);
            if (parentChapter == null) {
                // 同级章节的父章节不存在，添加失败
                return false;
            }
            // 如果存在，更新父级章节数量
            parentChapter.setChildCount(parentChapter.getChildCount() + 1);
            // 设置新章节的父章节
            newChapter.setParentId(parentId);
            if (!updateById(parentChapter)) flag = false;
        }

        // 设置新章节的层级、顺序、课程id
        newChapter.setRank(siblingChapter.getRank());
        newChapter.setSortOrder(siblingChapter.getSortOrder());
        newChapter.setCourseId(courseId);


        // 更新数据库  要先更新同级章节排序 再保存新的章节，更新父章节，
        return updateChapterSortOrder(parentId, siblingChapter, 0, 1) && save(newChapter) && flag;
    }

    /**
     * @Author hjy
     * @Description //TODO
     * @Date 3:57 2023/4/17
     * @Param chapterId 章节id
     * @Param newTitle 新章节标题
     */
    @Override
    public boolean updateChapterTitleById(String chapterId, String newTitle) {
        Chapter chapter = new Chapter();
        chapter.setChapterId(chapterId);
        chapter.setChapterTitle(newTitle);
        return updateById(chapter);
    }

    /**
     * 获取某章节的子章节列表
     *
     * @param chapter 章节实体类
     * @return 子章节列表
     */
    private List<Chapter> getChildrenChapter(Chapter chapter) {
        // 定义一个返回章节列表，便于后续返回，如果直接添加会造成一边遍历一边修改
        List<Chapter> ruturnChaptersList = new ArrayList<>();
        if (chapter.getChildCount() > 0) {
            // 查询要该章节及其子章节
            List<Chapter> chaptersList = chapterMapper.selectList(
                    new QueryWrapper<Chapter>().eq("parent_id", chapter.getChapterId())
            );
            // 递归获取子章节
            for (Chapter chapterVo : chaptersList) {
                if (chapter.getChildCount() > 0) {
                    ruturnChaptersList.addAll(getChildrenChapter(chapterVo));
                }
            }
        }
        return ruturnChaptersList;
    }

    @Override
    public boolean deleteChapterById(String chapterId) {
        // 先找到该章节
        Chapter chapter = getById(chapterId);
        // 找到该章节的所有子章节列表
        List<Chapter> chaptersToDelete = getChildrenChapter(chapter);
        // 往该待删除的章节列表添加本章节
        chaptersToDelete.add(chapter);
        // 更新父章节的childCount
        boolean updateFlag = true;
        if (!chapter.getParentId().equals("0")) {
            updateFlag = updateParentChapterChildCount(chapter);
        }
        // 先更新该章节同级章节sortOrder ,再批量删除该章节
        return updateChapterSortOrder(chapter.getParentId(), chapter, 1, -1) && removeBatchByIds(chaptersToDelete.stream().map(Chapter::getChapterId).collect(Collectors.toList())) && updateFlag;
    }

    @Override
    public boolean deleteChapterByCourseId(String courseId) {

        QueryWrapper<Chapter> queryWrapper = new QueryWrapper<Chapter>();
        queryWrapper.eq("course_id", courseId);
        if (chapterMapper.selectList(queryWrapper).size() > 0) {
            return remove(queryWrapper);
        } else
            return true;

    }

    private Boolean updateParentChapterChildCount(Chapter chapter) {
        String parentId = chapter.getParentId();
        if (!parentId.equals("0")) {
            Chapter parentChapter = chapterMapper.selectById(parentId);
            parentChapter.setChildCount(parentChapter.getChildCount() - 1);
            return updateById(parentChapter);
        }
        return true;
    }


    private boolean updateChapterSortOrder(String parentId, Chapter siblingChapter, Integer begin_index, Integer addOrSub) {
        // 获取同级章节列表
        List<Chapter> siblings = chapterMapper.selectList(
                new QueryWrapper<Chapter>().eq("parent_id", parentId).orderByAsc("sort_order"));
        // 在同级章节列列表中找到兄弟章节索引,减少遍历次数
        int index = siblings.indexOf(siblingChapter);
        // 更新同级章节的顺序
        for (int i = index + begin_index; i < siblings.size(); i++) {
            System.out.println(i);
            siblings.get(i).setSortOrder(siblings.get(i).getSortOrder() + addOrSub);
        }
        return updateBatchById(siblings);
    }

    private List<Chapter> getChildrenChapter1(Chapter chapter, String parentIndex) {
        List<Chapter> returnChaptersList = new ArrayList<>();

        if (chapter.getChildCount() > 0) {
            // Query the chapter and its children
            List<Chapter> chaptersList = chapterMapper.selectList(
                    new QueryWrapper<Chapter>().eq("parent_id", chapter.getChapterId())
            );

            // Iterate over the chapters and add index
            for (int i = 0; i < chaptersList.size(); i++) {
                Chapter chapterVo = chaptersList.get(i);
                String chapterIndex = parentIndex + (i + 1) + ". ";

                // Append the index to the chapter title
                chapterVo.setChapterTitle(chapterIndex + chapterVo.getChapterTitle());

                // Recursive call to add index for children chapters
                if (chapterVo.getChildCount() > 0) {
                    List<Chapter> childrenChapters = getChildrenChapter1(chapterVo, chapterIndex);
                    returnChaptersList.addAll(childrenChapters);
                }

                returnChaptersList.add(chapterVo);
            }
        }

        return returnChaptersList;
    }

    @Override
    public Integer getCourseTask(String courseId) {
        LambdaQueryWrapper<Chapter> queryChainWrapper = new LambdaQueryWrapper<>();
        queryChainWrapper.eq(Chapter::getCourseId, courseId);
        queryChainWrapper.select(Chapter::getVideoCount);
        List<Chapter> list = list(queryChainWrapper);
        return list.stream()
                .mapToInt(Chapter::getVideoCount)
                .sum();
    }

    @Override
    public List<ChapterNode> getChapterByClassId(String classId, String courseId) {
        Map<String, ChapterNode> chapterNodeMap = getChapterNodeList(courseId, null);
        Map<String, Long> chapterTaskCountMap = taskUserService.getTaskByClassID(courseId, classId);
        Integer classStudentCount = 10;
//        for (ChapterNode chapter : chapterNodeMap.values()) {
//            if (chapter.getVideoCount() == 0) continue;
//            Long chapterTaskCount = chapterTaskCountMap.getOrDefault(chapter.getChapterId(), 0L);
//            if (chapterTaskCount != 0L) {
//                System.out.println(chapterTaskCount);
//                Integer chapterTotalTaskCount = classStudentCount * chapter.getVideoCount();
//
//                double taskCompleteionRate = chapterTaskCount / (double) chapterTotalTaskCount;
//                System.out.println();
//                String taskCompleteionRateStr = String.format("%.2f", taskCompleteionRate * 100);
//                double taskCompleteionRateDouble = Double.parseDouble(taskCompleteionRateStr);
//                chapter.setCompletionRate(taskCompleteionRateDouble);
//                System.out.println(chapterTotalTaskCount);
//                System.out.println(chapter);
//            }
//            ;
//        }
        chapterNodeMap.values().stream()
                .filter(chapter -> chapter.getVideoCount() > 0)
                .forEach(chapter -> {
                    Long chapterTaskCount = chapterTaskCountMap.getOrDefault(chapter.getChapterId(), 0L);
                    if (chapterTaskCount != 0L) {
                        System.out.println(chapterTaskCount);
                        int chapterTotalTaskCount = classStudentCount * chapter.getVideoCount();
                        double taskCompletionRate = chapterTaskCount / (double) chapterTotalTaskCount;
                        System.out.println();
                        String taskCompletionRateStr = String.format("%.2f", taskCompletionRate * 100);
                        double taskCompletionRateDouble = Double.parseDouble(taskCompletionRateStr);
                        chapter.setCompletionRate(taskCompletionRateDouble);
                    }
                });
        return buildChapterTreeNode(chapterNodeMap);
    }

}
